import { closeLoading, showLoading } from '@/utils/loading'
import axios from 'axios'
import { regionNums } from '@/utils/buildingRegionEnum'
import { cloneDeep } from 'lodash'

export function useBuildingAge() {
  let map = null
  let styleJson = null
  let legendList = []
  let addedLayerIds = []
  let highlightLayerIds = []
  /**
   * 初始化
   */
  const init = (_map) => {
    map = _map
  }

  /**
   * 获取服务的styleJson
   */
  const fetchServiceStyleJson = async () => {
    if (styleJson) {
      return styleJson
    }
    try {
      const res = await axios.get(window.buildingAgeServiceUrl)
      if (res.status === 200) {
        styleJson = res.data
        return styleJson
      } else {
        return null
      }
    } catch (e) {
      console.error(e)
      return null
    }
  }

  /**
   * 添加服务
   */
  const addBuildingAgeService = async () => {
    showLoading()
    await fetchServiceStyleJson()
    addSourceLayer(styleJson)
    closeLoading()
  }

  /**
   * 添加服务图层
   */
  const addSourceLayer = (
    styleJson
  ) => {
    Object.keys(styleJson.sources).forEach((sourceKey) => {
      if (!map.getSource(sourceKey)) {
        map.addSource(sourceKey, styleJson.sources[sourceKey])
      }
    })
    styleJson.layers.forEach((layer) => {
      if (!map.getLayer(layer.id)) {
        if (layer.layout?.visibility !== 'none') { // 仅添加未隐藏的图层
          map.addLayer(layer)
          addedLayerIds.push(layer.id)
          const highlightLayer = cloneDeep(layer)
          highlightLayer.id = highlightLayer.id + '_highlight'
          highlightLayer.filter = ['all', ['in', 'JZWBM', '']]
          highlightLayer.paint['fill-color'] = 'rgb(0,0,255)'
          highlightLayer.paint['fill-outline-color'] = 'rgb(0,0,255)'
          highlightLayerIds.push(highlightLayer.id)
          map.addLayer(highlightLayer)
        }
      }
    })

  }

  /**
   * 移除服务图层
   */
  const removeSourceLayer = () => {
    if (!addedLayerIds.length) {
      return
    }
    addedLayerIds.forEach((id) => {
      if (map.getLayer(id)) {
        map.removeLayer(id)
      }
    })
    highlightLayerIds.forEach((layerId) => {
      if (map.getLayer(layerId)) {
        map.removeLayer(layerId)
      }
    })
    addedLayerIds = []
    highlightLayerIds = []
  }
  // 设置高亮
  const setBuildingHighlight = (ids) => {
    highlightLayerIds.forEach((layerId) => {
      if (map.getLayer(layerId)) {
        map.setFilter(layerId, ['in', 'JZWBM', ...ids])
      }
    })
  }

  /**
   * 获取服务图例列表
   */
  const getLegendList = async () => {
    if (legendList.length) {
      return legendList
    }
    // 过滤掉隐藏的图层
    legendList = styleJson.layers.filter((layer) => layer.layout?.visibility !== 'none').map((layer, index) => ({
      label: layer.id,
      value: index + ''
    }))
    return legendList
  }

  return {
    addBuildingAgeService,
    getLegendList,
    init,
    removeSourceLayer,
    setBuildingHighlight
  }
}
